package com.cloudinnov.logic.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.cloudinnov.aop.SystemLog;
import com.cloudinnov.dao.EquipmentsDao;
import com.cloudinnov.dao.PredictionRuleTableDao;
import com.cloudinnov.logic.BxManagerLogic;
import com.cloudinnov.logic.ControlSolutionLogic;
import com.cloudinnov.logic.EquipmentControlLogic;
import com.cloudinnov.logic.EquipmentsLogic;
import com.cloudinnov.logic.PredictionRuleLogLogic;
import com.cloudinnov.logic.PredictionRuleTableLogic;
import com.cloudinnov.logic.SectionLogic;
import com.cloudinnov.model.ControlSolution;
import com.cloudinnov.model.ControlSolutionConfig;
import com.cloudinnov.model.ControlSolutionConfig.Config;
import com.cloudinnov.task.mq.FireMQConsumer;
import com.cloudinnov.model.Equipments;
import com.cloudinnov.model.PredictionContacter;
import com.cloudinnov.model.PredictionRuleLog;
import com.cloudinnov.model.PredictionRuleTable;
import com.cloudinnov.model.Section;
import com.cloudinnov.utils.CodeUtil;
import com.cloudinnov.utils.CommonUtils;
import com.cloudinnov.utils.JudgeNullUtil;
import com.cloudinnov.utils.RemoteControllerUtil;
import com.cloudinnov.utils.control.ControlModel;
import com.cloudinnov.utils.control.EquipmentControlLog;
import com.cloudinnov.websocket.PredictionAlarmWebsocket;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service("predictionRuleTableLogic")
public class PredictionRuleTableLogicImpl extends BaseLogicImpl<PredictionRuleTable>
		implements PredictionRuleTableLogic {

	static final Logger LOG = LoggerFactory.getLogger(PredictionRuleTableLogicImpl.class);
	// 设备分类标识
	static final String JBZM = "JBZM";
	static final String JQZM = "JQZM";
	static final String YJZM = "YJZM";
	static final String QBB = "QBB";
	static final String SDFJ = "SDFJ";
	static final String CDZSQ = "CDZSQ";
	static final String HDJIM = "HDJIM";
	static final String JTXHD = "JTXHD";

	// json的key值
	static final String SIGN = "sign";
	static final String TITTLE = "tittle";
	static final String EQUIPMENTS = "equipments";
	static final String PREDICTIONNAME = "predictionName";
	static final String PREDICTIONEQUIPMENTS = "predictionEquipments";
	static final Integer SUCCESS = 1;
	static final Integer ERROR = 0;
	public static final Integer digit = 5;

	@Autowired
	private PredictionRuleTableDao predictionRuleTableDao;
	@Autowired
	private EquipmentsLogic equipmentsLogic;
	@Autowired
	private EquipmentsDao equipmentsDao;
	@Autowired
	private EquipmentControlLogic equipmentControlLogic;
	@Autowired
	private PredictionRuleTableLogic predictionRuleTableLogic;
	@Autowired
	private SectionLogic sectionLogic;
	@Autowired
	private ControlSolutionLogic controlSolutionLogic;
	@Autowired
	private PredictionRuleLogLogic predictionRuleLogLogic;
	@Autowired
	private BxManagerLogic bxManagerLogic;

	@Override
	public List<PredictionRuleTable> selectPredictions(PredictionRuleTable predictionRuleTable) {
		List<PredictionRuleTable> predictionRules = predictionRuleTableDao.selectPredictionsRule(predictionRuleTable);
		return predictionRules;
	}

	/**
	 * 动态获取预案恢复方案和发送控制命令方法
	 */
	@Override
	public Map<String, Object> achieveAndSendRecoverPredictionRules(PredictionRuleTable predictionRuleTable) {
		predictionRuleTable.setAccidentType(null);
		Map<String, Object> allMap = new HashMap<>();
		List<Map<String, Object>> resultList = new ArrayList<>();
		// 带控制命令的设备集合
		List<Equipments> ruleEquipments = new ArrayList<>();
		List<PredictionRuleTable> predictionRules = predictionRuleTableDao.selectPredictionsRule(predictionRuleTable);
		if (JudgeNullUtil.iList(predictionRules)) {
			for (PredictionRuleTable predictionRule : predictionRules) {
				// 调用方法查询设备并把控制命令添加上
				List<Equipments> equipments = getEquipmentsByPredictionRule(predictionRule);
				for (Equipments equipment : equipments) {
					ruleEquipments.add(equipment);
				}
			}
		} else {
			LOG.warn("动态查询预案恢复方案为空!");
		}
		// 获取带有控制命令的设备后,往bolomi发送控制命令
		if (JudgeNullUtil.iList(ruleEquipments)) {

			for (Equipments ruleEquipment : ruleEquipments) {
				Map<String, Object> resultMap = new HashMap<>();
				String categoryCode = ruleEquipment.getCategoryCode();
				if (categoryCode.contains(QBB)) {
					String solutionCode = ruleEquipment.getSolutionCode();
					int result = bxManagerLogic.forcedToInforBorad(solutionCode);
					if (result == 1) {
						resultMap.put("code", ruleEquipment.getCode());
						resultMap.put("status", 1);
						resultList.add(resultMap);
					}else {
						resultMap.put("code", ruleEquipment.getCode());
						resultMap.put("status", 0);
						resultList.add(resultMap);
					}
				} else {
					List<ControlModel> commonds = equipmentControlLogic.generateControllerCommond(ruleEquipment);
					if (JudgeNullUtil.iList(commonds)) {
						EquipmentControlLog equipCtrlLog = RemoteControllerUtil.controller(commonds); // 单个设备命令发往bolomi发命令的方法
						Integer result = equipCtrlLog.getCode();
						if (result != null) {
							resultMap.put("code", ruleEquipment.getCode());
							resultMap.put("status", 1);
							resultList.add(resultMap);
						} else {
							resultMap.put("code", ruleEquipment.getCode());
							resultMap.put("status", 0);
							resultList.add(resultMap);
						}
					}
				}
			}
		}
		allMap.put(PREDICTIONEQUIPMENTS, ruleEquipments);
		allMap.put(SIGN, resultList);
		return allMap;
	}

	/**
	 * 根据设备分类和section查询设备
	 * 
	 * @param predictionRule
	 * @return 返回带控制命令的设备集合
	 */
	public List<Equipments> getEquipmentsByPredictionRule(PredictionRuleTable predictionRule) {
		String categoryCode = predictionRule.getCategoryCode();
		List<Equipments> equipmentList = new ArrayList<>();
		if (categoryCode != null
				&& (categoryCode.startsWith(JBZM) || categoryCode.startsWith(JQZM) || categoryCode.startsWith(YJZM)) || categoryCode.startsWith(JTXHD)) {
			String config = predictionRule.getConfig();

			Equipments equipment = new Equipments();
			equipment.setSectionCode(predictionRule.getSectionCode());
			equipment.setCategoryCode(predictionRule.getCategoryCode());
			equipment.setAreaId(predictionRule.getAreaId());
			equipmentList = equipmentsLogic.selectEquipsBySectionAndCategory(equipment);
			if (equipmentList != null) {
				for (Equipments equipControl : equipmentList) {
					List<ControlSolutionConfig.Config> configs = new ArrayList<>();
					if (CommonUtils.isNotEmpty(config)) {
						configs.addAll(JSON.parseArray(config, ControlSolutionConfig.Config.class));
					}
					equipControl.setConfig(configs);
					equipControl.setCommand(config);
				}
			} else {
				LOG.warn(categoryCode + "预案动态匹配设备结果为空!");
			}
		}else if (categoryCode.contains(QBB)) {
			String solutionCode = predictionRule.getConfig();
			if (JudgeNullUtil.iStr(solutionCode)) {
				//调用查询情报板的方法
				ControlSolution controlSolution = new ControlSolution();
				controlSolution.setCode(solutionCode);
				Map<String, Object> boardSolution = controlSolutionLogic.selectBoardSolution(controlSolution);
				Equipments equipment = new Equipments();
				equipment.setSectionCode(predictionRule.getSectionCode());
				equipment.setCategoryCode(predictionRule.getCategoryCode());
				equipment.setAreaId(predictionRule.getAreaId());
				equipmentList = equipmentsLogic.selectEquipsBySectionAndCategory(equipment);
				if (JudgeNullUtil.iList(equipmentList)) {
					for (Equipments equipControl : equipmentList) {
						equipControl.setBoardConfig(boardSolution);
						equipControl.setSolutionCode(solutionCode);
					}
				}
			} else {
				LOG.error("情报板设备的控制命令没有存储,查询为null!");
			}
		} else if (categoryCode.contains(CDZSQ)) {
			String config = predictionRule.getConfig();
			String lane = predictionRule.getLane(); //车道指示器所在的车道
			
			Equipments equipment = new Equipments();
			equipment.setSectionCode(predictionRule.getSectionCode());
			equipment.setCategoryCode(predictionRule.getCategoryCode());
			equipment.setAreaId(predictionRule.getAreaId());
			if (JudgeNullUtil.iStr(lane) && JudgeNullUtil.iList(equipmentList)) { //如果有车道数
				equipment.setLane(lane); 
			}
			//在已知的车道下查询事故区域的设备
			equipmentList = equipmentsLogic.selectEquipsBySectionAndCategoryAndLaneAndAreaId(equipment);
			
			if (equipmentList != null) {
				for (Equipments equipControl : equipmentList) {
					List<ControlSolutionConfig.Config> configs = new ArrayList<>();
					if (CommonUtils.isNotEmpty(config)) {
						configs.addAll(JSON.parseArray(config, ControlSolutionConfig.Config.class));
					}
					equipControl.setAreaId(predictionRule.getAreaId());
					equipControl.setConfig(configs);
					equipControl.setCommand(config);
					if (JudgeNullUtil.iStr(lane)) {
						equipControl.setLane(lane);
					}
				}
			} else {
				LOG.warn(categoryCode + "设备结果为空!");
			}
		} else if (categoryCode != null) {
			String config = predictionRule.getConfig();

			Equipments equipment = new Equipments();
			equipment.setSectionCode(predictionRule.getSectionCode());
			equipment.setCategoryCode(predictionRule.getCategoryCode());
			equipment.setAreaId(predictionRule.getAreaId());
			equipmentList = equipmentsLogic.selectEquipsBySectionAndCategory(equipment);
			if (equipmentList != null) {
				for (Equipments equipControl : equipmentList) {
					List<ControlSolutionConfig.Config> configs = new ArrayList<>();
					if (CommonUtils.isNotEmpty(config)) {
						configs.addAll(JSON.parseArray(config, ControlSolutionConfig.Config.class));
					}
					equipControl.setConfig(configs);
					equipControl.setCommand(config);
				}
			} else {
				LOG.warn(categoryCode + "预案动态匹配设备结果为空!");
			}
		} else {
			LOG.warn("预案规则表添加有误,返回的结果中没有设备分类!");
		}
		return equipmentList;
	}

	@Override
	public List<String> getAccidentTypes() {
		return predictionRuleTableDao.getAccidentTypes();
	}
	
	@SystemLog
	@Override
	public Map<String, Object> manTrigGetPredictionRules(String message) {
		Equipments equipment = JSON.parseObject(message, Equipments.class);
		Map<String, Object> prediction = new HashMap<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String predictionName = "";
		String alarmPosition = "";
		String alarmEquipName = "";
		String accidentArea = "";
		String accidentCameraCode = "";
		String alarmDate = sdf.format(new Date());
		if (equipment != null) {
			alarmPosition = equipment.getPileNo();
			if (equipment.getName() == null || equipment.getName() == "") {
				alarmEquipName = equipment.getEquipmentName();
			}else {
				alarmEquipName = equipment.getName();
			}
			
			accidentArea = equipment.getAreaId();
			accidentCameraCode = equipment.getCode();
			
			prediction.put("alarmPosition", alarmPosition);
			prediction.put("alarmDate", alarmDate);
			prediction.put("accidentArea", accidentArea);
			prediction.put("alarmEquipName", alarmEquipName);
			prediction.put("accidentCameraCode", accidentCameraCode);
			
			Map<String, Object> equipmentList1 = new HashMap<>();
			Map<String, Object> equipmentList2 = new HashMap<>();
			Map<String, Object> equipmentList3 = new HashMap<>();
			Map<String, Object> equipmentList4 = new HashMap<>();
			Map<String, Object> equipmentList5 = new HashMap<>();
			// 根据报警的位置动态获取预案
			PredictionRuleTable predictionRuleTable = new PredictionRuleTable();
			predictionRuleTable.setAccidentArea(equipment.getAreaId());
			predictionRuleTable.setSectionCode(equipment.getSectionCode());
			predictionRuleTable.setAccidentType(equipment.getAccidentType());
			// 动态生成预案名称
			predictionName = equipment.getSectionName() + equipment.getAreaId() + "事故区域" + equipment.getAccidentType() + "预案";
			
			//创建预案执行记录对象
			PredictionRuleLog predictionRuleLog = new PredictionRuleLog();
			//预案触发时出入预案执行记录数据
			String code = CodeUtil.predictionLogCode(digit);
			predictionRuleLog.setCode(code);
			predictionRuleLog.setAccidentType(FireMQConsumer.ACCIDENTTYPE);
			if ("QSSXT".equals(equipment.getCategoryCode())) {
				predictionRuleLog.setTriggerType("手动触发");
			} else {
				predictionRuleLog.setTriggerType("自动触发");
			}
			predictionRuleLog.setTriggerTime(alarmDate);
			//添加预案执行记录的事故区域
			predictionRuleLog.setAccidentArea(equipment.getAreaId());
			//添加预案执行记录的预案名称
			predictionRuleLog.setPredictionName(predictionName);
			//添加预案执行记录的触发设备名称
			predictionRuleLog.setAlarmEquipment(alarmEquipName);
			
			// 从预案规则表中查询出结果
			List<PredictionRuleTable> predictionRules = predictionRuleTableLogic.selectPredictions(predictionRuleTable);
			if (JudgeNullUtil.iList(predictionRules)) {
				List<Equipments> fbEquipments = new ArrayList<>(); // 1,情报板和信号灯设备
				List<Equipments> hdEquipments = new ArrayList<>(); // 2,横洞卷帘门设备
				List<Equipments> cdEquipments = new ArrayList<>(); // 3,车道指示器设备
				List<Equipments> lightEquipments = new ArrayList<>(); // 4,照明设备
				List<Equipments> fjEquipments = new ArrayList<>(); // 5,隧道内风机,广播设备

				for (PredictionRuleTable predictionRule : predictionRules) {
					String categoryCode = predictionRule.getCategoryCode();
					if (categoryCode.startsWith(JBZM) || categoryCode.startsWith(JQZM) || categoryCode.startsWith(YJZM)) {
						List<Equipments> equipments = getEquipmentsByPredictionRule(predictionRule);
						for (Equipments equip : equipments) {
							lightEquipments.add(equip);
						}
					} else if (categoryCode.startsWith(HDJIM)) {
						List<Equipments> equipments = getEquipmentsByPredictionRule(predictionRule);
						for (Equipments equip : equipments) {
							hdEquipments.add(equip);
						}
					} else if (categoryCode.startsWith(SDFJ)) {
						List<Equipments> equipments = getEquipmentsByPredictionRule(predictionRule);
						for (Equipments equip : equipments) {
							fjEquipments.add(equip);
						}
					} else if (categoryCode.startsWith(CDZSQ)) {
						List<Equipments> equipments = getEquipmentsByPredictionRule(predictionRule);
						for (Equipments equip : equipments) {
							cdEquipments.add(equip);
						}
					} else if (categoryCode.startsWith(JTXHD) || categoryCode.contains(QBB)) {
						List<Equipments> equipments = getEquipmentsByPredictionRule(predictionRule);
						for (Equipments equip : equipments) {
							fbEquipments.add(equip);
						}
						// } else if (categoryCode.startsWith(prefix)) { // 洞内可变情报板
						// List<Equipments> equipments = getEquipmentsByPredictionRule(predictionRule);
						// for (Equipments equipment : equipments) {
						// fbEquipments.add(equipment);
						// }
					} else if (categoryCode == null) {
						LOG.error("预案规则表查询结果为空,出错!");
					}
				}
				equipmentList1.put(TITTLE, "关闭事故隧道,发布信息");
				equipmentList1.put(EQUIPMENTS, fbEquipments);
				equipmentList2.put(TITTLE, "控制横洞卷帘门");
				equipmentList2.put(EQUIPMENTS, hdEquipments);
				equipmentList3.put(TITTLE, "交通管制");
				equipmentList3.put(EQUIPMENTS, cdEquipments);
				equipmentList4.put(TITTLE, "开启照明设备");
				equipmentList4.put(EQUIPMENTS, lightEquipments);
				equipmentList5.put(TITTLE, "控制风机设备");
				equipmentList5.put(EQUIPMENTS, fjEquipments);
				List<Map<String, Object>> predictionEquipments = new ArrayList<>();
				predictionEquipments.add(equipmentList1);
				predictionEquipments.add(equipmentList2);
				predictionEquipments.add(equipmentList3);
				predictionEquipments.add(equipmentList4);
				predictionEquipments.add(equipmentList5);

				//返回预案执行记录的code,用于添加详细记录信息
				prediction.put("predictionRuleLog", predictionRuleLog);
				prediction.put(PREDICTIONNAME, predictionName);
				prediction.put(PREDICTIONEQUIPMENTS, predictionEquipments);
			}else {
				LOG.error("预案规则表中没有该事故区域的预案,请先添加!");
			}
		}else {
			LOG.error("前端传递的参数有误,请检查!");
		}
		return prediction;
	}

	@Override
	public Page<PredictionContacter> selectPredictionContacter(PredictionContacter predictionContacter, int index, int size) {
		PageHelper.startPage(index, size);
		PageHelper.orderBy("create_time desc");
		List<PredictionContacter> selectPredictionContacter = predictionRuleTableDao.selectPredictionContacter(predictionContacter);
		return (Page<PredictionContacter>)selectPredictionContacter;
	}

	@Override
	public int insertContacters(PredictionContacter predictionContacter) {
		String contacterCode = CodeUtil.contacterCode(digit);// 创建紧急联系人表达式code
		predictionContacter.setCode(contacterCode);
		predictionContacter.setStatus(1);
		long timeMillis = System.currentTimeMillis();
		predictionContacter.setCreateTime(timeMillis + "");
		return predictionRuleTableDao.insertContacters(predictionContacter);
	}
	
	@Override
	public int updateContacters(PredictionContacter predictionContacter) {
		long timeMillis = System.currentTimeMillis();
		predictionContacter.setCreateTime(timeMillis + "");
		return predictionRuleTableDao.updateContacters(predictionContacter);
	}
	
	@Override
	public int deleteContacters(PredictionContacter predictionContacter) {
		return predictionRuleTableDao.deleteContacters(predictionContacter);
	}
	
	@Override
	public int insertPredictionRule(PredictionRuleTable predictionRuleTable) {
		//判断是否存在重复值结果集
		List<Integer> existResults = new ArrayList<>();
		//判断返回值集合
		List<Integer> returnResults = new ArrayList<>();
		int flag = 1;
		PredictionRuleTable insertPredictionRuleTable = null;
		//添加预案的业务层实现类
		if (predictionRuleTable != null) {
			String categoryConfigs = predictionRuleTable.getCategoryConfigs();
			List<Equipments> configEquipments = JSON.parseArray(categoryConfigs, Equipments.class);
			if (JudgeNullUtil.iList(configEquipments)) {
				//判断添加的数据中是否有重复数据
				for (int i = 0; i < configEquipments.size(); i++) {
					insertPredictionRuleTable = new PredictionRuleTable();
					insertPredictionRuleTable.setAccidentType(predictionRuleTable.getAccidentType());
					insertPredictionRuleTable.setAccidentArea(predictionRuleTable.getAccidentArea());
					insertPredictionRuleTable.setSectionCode(predictionRuleTable.getSectionCode());
					insertPredictionRuleTable.setCategoryCode(configEquipments.get(i).getCategoryCode());
					insertPredictionRuleTable.setAreaId(configEquipments.get(i).getAreaId());
					String lane = configEquipments.get(i).getLane();
					if (JudgeNullUtil.iStr(lane)) {
						insertPredictionRuleTable.setLane(lane);
					}
					insertPredictionRuleTable.setIsRecover(predictionRuleTable.getIsRecover());
					Section section = new Section();
					section.setCode(predictionRuleTable.getSectionCode());
					section = sectionLogic.select(section);
					String predictionName = section.getName() + predictionRuleTable.getAccidentArea() + "事故区域" + predictionRuleTable.getAccidentType() + "预案";
					insertPredictionRuleTable.setPredictionName(predictionName);
					List<PredictionRuleTable> predictionRuleTables = predictionRuleTableDao.judgeIsExistPredictionRule(insertPredictionRuleTable);
					if (JudgeNullUtil.iList(predictionRuleTables)) {
						existResults.add(1);
					} else {
						existResults.add(0);
					}
				}
				boolean tag = true;
				//对是否存在重复值进行判断
				for (int i = 0; i < existResults.size(); i++) {
					if (existResults.get(i) == 1) {
						tag = false;
						break;
					}
				}
				if (tag) {	//判断添加的数据中没有重复的记录,执行添加操作
					for (int i = 0; i < configEquipments.size(); i++) {
						insertPredictionRuleTable = new PredictionRuleTable();
						String config = configEquipments.get(i).getCommand();  //前端给设备分类的控制命令属性值
						//对情报板设备的控制是获取它的solutionCode
						if (configEquipments.get(i).getCategoryCode().contains("QBB")) {
							String substring = config.substring(config.indexOf(":"), config.lastIndexOf("}"));
							config = substring.substring(substring.indexOf("\"")+1, substring.lastIndexOf("\""));
						}
						insertPredictionRuleTable.setConfig(config);
						insertPredictionRuleTable.setAccidentType(predictionRuleTable.getAccidentType());
						insertPredictionRuleTable.setAccidentArea(predictionRuleTable.getAccidentArea());
						insertPredictionRuleTable.setSectionCode(predictionRuleTable.getSectionCode());
						insertPredictionRuleTable.setCategoryCode(configEquipments.get(i).getCategoryCode());
						insertPredictionRuleTable.setAreaId(configEquipments.get(i).getAreaId());
						String lane = configEquipments.get(i).getLane();
						if (JudgeNullUtil.iStr(lane)) {
							insertPredictionRuleTable.setLane(lane);
						}
						insertPredictionRuleTable.setIsRecover(predictionRuleTable.getIsRecover());
						Section section = new Section();
						section.setCode(predictionRuleTable.getSectionCode());
						section = sectionLogic.select(section);
						String predictionName = section.getName() + predictionRuleTable.getAccidentArea() + "事故区域" + predictionRuleTable.getAccidentType() + "预案";
						insertPredictionRuleTable.setPredictionName(predictionName);
						int rusult = predictionRuleTableDao.insertPredictionRule(insertPredictionRuleTable);
						returnResults.add(rusult);
					}
					
					//对添加的结果进行判断
					if (JudgeNullUtil.iList(returnResults)) {
						for (int i = 0; i < returnResults.size(); i++) {
							if (returnResults.get(i) != 1) {
								flag = 0;
							}
						}
					}else {
						flag = 0;
					}
				} else {	//判断添加的数据中有重复的记录,对标识符赋值
					flag = 0;
				}
			}
		}
		return flag;
	}
	
	@Override
	public int insertRecoverPredictionRule(PredictionRuleTable predictionRuleTable) {
		//判断是否存在重复值结果集
		List<Integer> existResults = new ArrayList<>();
		//判断返回值集合
		List<Integer> returnResults = new ArrayList<>();
		int flag = 1;
		PredictionRuleTable insertPredictionRuleTable = null;
		//添加预案的业务层实现类
		if (predictionRuleTable != null) {
			String categoryConfigs = predictionRuleTable.getCategoryConfigs();
			List<Equipments> configEquipments = JSON.parseArray(categoryConfigs, Equipments.class);
			if (JudgeNullUtil.iList(configEquipments)) {
				//对添加的数据进行重复判断
				for (int i = 0; i < configEquipments.size(); i++) {
					insertPredictionRuleTable = new PredictionRuleTable();
					insertPredictionRuleTable.setSectionCode(predictionRuleTable.getSectionCode());
					insertPredictionRuleTable.setCategoryCode(configEquipments.get(i).getCategoryCode());
					insertPredictionRuleTable.setAreaId(configEquipments.get(i).getAreaId());
					String lane = configEquipments.get(i).getLane();
					if (JudgeNullUtil.iStr(lane)) {
						insertPredictionRuleTable.setLane(lane);
					}
					insertPredictionRuleTable.setIsRecover(predictionRuleTable.getIsRecover());
					Section section = new Section();
					section.setCode(predictionRuleTable.getSectionCode());
					section = sectionLogic.select(section);
					String predictionName = section.getName() + "恢复预案";
					insertPredictionRuleTable.setPredictionName(predictionName);
					List<PredictionRuleTable> predictionRuleTables = predictionRuleTableDao.judgeIsExistPredictionRule(insertPredictionRuleTable);
					if (JudgeNullUtil.iList(predictionRuleTables)) {
						existResults.add(1);
					} else {
						existResults.add(0);
					}
				}
				boolean tag = true;
				//对是否存在重复值进行判断
				for (int i = 0; i < existResults.size(); i++) {
					if (existResults.get(i) == 1) {
						tag = false;
						break;
					}
				}
				if (tag) {	//没有重复记录,进行添加操作
					for (int i = 0; i < configEquipments.size(); i++) {
						insertPredictionRuleTable = new PredictionRuleTable();
						String config = configEquipments.get(i).getCommand();  //前端给设备分类的控制命令属性值
						if (configEquipments.get(i).getCategoryCode().contains("QBB")) {
							String substring = config.substring(config.indexOf(":"), config.lastIndexOf("}"));
							config = substring.substring(substring.indexOf("\"")+1, substring.lastIndexOf("\""));
						}
						insertPredictionRuleTable.setConfig(config);
						insertPredictionRuleTable.setSectionCode(predictionRuleTable.getSectionCode());
						insertPredictionRuleTable.setCategoryCode(configEquipments.get(i).getCategoryCode());
						insertPredictionRuleTable.setAreaId(configEquipments.get(i).getAreaId());
						String lane = configEquipments.get(i).getLane();
						if (JudgeNullUtil.iStr(lane)) {
							insertPredictionRuleTable.setLane(lane);
						}
						insertPredictionRuleTable.setIsRecover(predictionRuleTable.getIsRecover());
						Section section = new Section();
						section.setCode(predictionRuleTable.getSectionCode());
						section = sectionLogic.select(section);
						String predictionName = section.getName() + "恢复预案";
						insertPredictionRuleTable.setPredictionName(predictionName);
						List<PredictionRuleTable> predictionRuleTables = predictionRuleTableDao.judgeIsExistPredictionRule(insertPredictionRuleTable);
						if (JudgeNullUtil.iList(predictionRuleTables)) {
							break;
						} else {
							int rusult = predictionRuleTableDao.insertPredictionRule(insertPredictionRuleTable);
							returnResults.add(rusult);
						}
					}
					//对添加结果的判断
					if (JudgeNullUtil.iList(returnResults)) {
						for (int i = 0; i < returnResults.size(); i++) {
							if (returnResults.get(i) != 1) {
								flag = 0;
							}
						}
					}else {
						flag = 0;
					}
				} else {	//有重复记录,对标识符赋值
					flag = 0;
				}
			}
		}
		return flag;
	}

	@Override
	public Page<PredictionRuleTable> selectPredictionRule(PredictionRuleTable model, int index, int size) {
		PageHelper.startPage(index, size);
		//查询预案表中所有的预案
		List<PredictionRuleTable> predictionRuleTables = predictionRuleTableDao.selectPredictionRule(model);
		return (Page<PredictionRuleTable>)predictionRuleTables;
	}

	@Override
	public PredictionRuleTable selectSinglePredictionRule(PredictionRuleTable model) {
		List<Equipments> equipmentInfo = new ArrayList<>();
		List<PredictionRuleTable> predictionRules = predictionRuleTableDao.selectSinglePredictionRule(model);
		if (JudgeNullUtil.iList(predictionRules)) {
			for (PredictionRuleTable predictionRuleTable : predictionRules) {
				Equipments equipment = new Equipments();
				equipment.setCategoryCode(predictionRuleTable.getCategoryCode());
				equipment.setSectionCode(predictionRuleTable.getSectionCode());
				equipment.setAreaId(predictionRuleTable.getAreaId());
				if (predictionRuleTable.getCategoryCode().contains("QBB")) {
					List<Equipments> equipments = equipmentsLogic.selectEquipsBySectionAndCategory(equipment);
					//情报板分类时,控制命令的存储形式
					for (int i = 0; i < equipments.size(); i++) {
						String solutionCode = predictionRuleTable.getConfig();
						//调用查询情报板的方法
						ControlSolution controlSolution = new ControlSolution();
						controlSolution.setCode(solutionCode);
						Map<String, Object> boardSolution = controlSolutionLogic.selectBoardSolution(controlSolution);
						equipments.get(i).setBoardConfig(boardSolution);
						equipmentInfo.add(equipments.get(i));
						break;
					}
				} else { //请他设备分类的形式
					List<Equipments> equipments = equipmentsLogic.selectEquipsBySectionAndCategory(equipment);
					for (int i = 0; i < equipments.size(); i++) {
						List<ControlSolutionConfig.Config> configs = new ArrayList<>();
						//其他设备分类时,扣子命令的存储形式
						String config = predictionRuleTable.getConfig();
						//如果是车道器,查询所在的车道
						String lane = predictionRuleTable.getLane();
						if (CommonUtils.isNotEmpty(config)) {
							configs.addAll(JSON.parseArray(config, ControlSolutionConfig.Config.class));
						}
						if (JudgeNullUtil.iStr(lane)) {
							//查询车道指示器的所有车道数
							List<String> lanes = new ArrayList<>();
							List<Equipments> laneEquipments = equipmentsDao.selectLanesBySection(equipments.get(i));
							for (Equipments laneEquipment : laneEquipments) {
								if (laneEquipment.getLane() != null) {
									lanes.add(laneEquipment.getLane());
								}
							}
							equipments.get(i).setLane(lane);
							equipments.get(i).setLanes(lanes); 
						}
						equipments.get(i).setConfig(configs);
						equipments.get(i).setCommand(config);
						equipmentInfo.add(equipments.get(i));
						break;
					}
				}
				model.setCategoryConfig(equipmentInfo);
			}
		}
		return model;
	}
	
	@Override
	public int updatePredictionRule(PredictionRuleTable predictionRuleTable) {
		List<Integer> results = new ArrayList<>();
		int flag = 1;
		PredictionRuleTable insertPredictionRuleTable = null;
		//先删除原先的预案
		int result = predictionRuleTableDao.deletePredictionRule(predictionRuleTable);
		if (result != 0) {
			String categoryConfigs = predictionRuleTable.getCategoryConfigs();
			List<Equipments> configEquipments = JSON.parseArray(categoryConfigs, Equipments.class);
			if (JudgeNullUtil.iList(configEquipments)) {
				for (Equipments equipment : configEquipments) {
					insertPredictionRuleTable = new PredictionRuleTable();
					String config = equipment.getCommand(); //前端给设备分类的控制命令属性值
					if (equipment.getCategoryCode().contains("QBB")) {
						String substring = config.substring(config.indexOf(":"), config.lastIndexOf("}"));
						config = substring.substring(substring.indexOf("\"")+1, substring.lastIndexOf("\""));
					}
					insertPredictionRuleTable.setConfig(config);
					insertPredictionRuleTable.setAccidentType(predictionRuleTable.getAccidentType());
					insertPredictionRuleTable.setAccidentArea(predictionRuleTable.getAccidentArea());
					insertPredictionRuleTable.setSectionCode(predictionRuleTable.getSectionCode());
					insertPredictionRuleTable.setCategoryCode(equipment.getCategoryCode());
					insertPredictionRuleTable.setAreaId(equipment.getAreaId());
					String lane = equipment.getLane();
					if (JudgeNullUtil.iStr(lane)) {
						insertPredictionRuleTable.setLane(lane);
					}
					Section section = new Section();
					section.setCode(predictionRuleTable.getSectionCode());
					section = sectionLogic.select(section);
					String predictionName = section.getName() + predictionRuleTable.getAccidentArea() + "事故区域" + predictionRuleTable.getAccidentType() + "预案";
					insertPredictionRuleTable.setPredictionName(predictionName);
					insertPredictionRuleTable.setIsRecover(predictionRuleTable.getIsRecover());
					int rusult = predictionRuleTableDao.insertPredictionRule(insertPredictionRuleTable);
					results.add(rusult);
				}
			}
			if (JudgeNullUtil.iList(results)) {
				for (int i = 0; i < results.size(); i++) {
					if (results.get(i) != 1) {
						flag = 0;
					}
				}
			}
		}
		return flag;
	}
	
	@Override
	public int updateRecoverPredictionRule(PredictionRuleTable predictionRuleTable) {
		List<Integer> results = new ArrayList<>();
		int flag = 1;
		PredictionRuleTable insertPredictionRuleTable = null;
		//先删除原先的预案
		int result = predictionRuleTableDao.deletePredictionRule(predictionRuleTable);
		if (result != 0) {
			String categoryConfigs = predictionRuleTable.getCategoryConfigs();
			List<Equipments> configEquipments = JSON.parseArray(categoryConfigs, Equipments.class);
			if (JudgeNullUtil.iList(configEquipments)) {
				for (Equipments equipment : configEquipments) {
					insertPredictionRuleTable = new PredictionRuleTable();
					String config = equipment.getCommand(); //前端给设备分类的控制命令属性值
					if (equipment.getCategoryCode().contains("QBB")) {
						String substring = config.substring(config.indexOf(":"), config.lastIndexOf("}"));
						config = substring.substring(substring.indexOf("\"")+1, substring.lastIndexOf("\""));
					}
					insertPredictionRuleTable.setConfig(config);
					insertPredictionRuleTable.setSectionCode(predictionRuleTable.getSectionCode());
					insertPredictionRuleTable.setCategoryCode(equipment.getCategoryCode());
					insertPredictionRuleTable.setAreaId(equipment.getAreaId());
					String lane = equipment.getLane();
					if (JudgeNullUtil.iStr(lane)) {
						insertPredictionRuleTable.setLane(lane);
					}
					Section section = new Section();
					section.setCode(predictionRuleTable.getSectionCode());
					section = sectionLogic.select(section);
					String predictionName = section.getName() + "恢复预案";
					insertPredictionRuleTable.setPredictionName(predictionName);
					insertPredictionRuleTable.setIsRecover(predictionRuleTable.getIsRecover());
					int rusult = predictionRuleTableDao.insertPredictionRule(insertPredictionRuleTable);
					results.add(rusult);
				}
			}
			if (JudgeNullUtil.iList(results)) {
				for (int i = 0; i < results.size(); i++) {
					if (results.get(i) != 1) {
						flag = 0;
					}
				}
			}
		}
		return flag;
	}
	
	@Override
	public int deletePredictionRule(PredictionRuleTable predictionRuleTable) {
		int result = 0;
		if (predictionRuleTable != null) {
			result = predictionRuleTableDao.deletePredictionRule(predictionRuleTable);
		}
		if (result != 0) {
			result = 1;
		}
		return result;
	}

}
